#include "historyrecord.h"
#include "ui_historyrecord.h"

#include <QMessageBox>
#include <QSqlQuery>
#include <QFile>
#include <QDebug>
#include <QStringList>
#include <QString>
#include <QSqlDatabase>
#include <QSqlQueryModel>
#include <QTableView>
#include <QtDebug>
#include <QMetaType>
#include <QObject>
#include <QMutex>
#include <QVector>
#include <QSet>
#include <QMenu>
#include <QThread>
#include <QWidget>
#include <QModelIndex>
#include <QSqlRecord>
#include <QSqlError>
#include <QIcon>
#include <QEventLoop>


#define Q(a)    qDebug()<<a;

HistoryRecord::HistoryRecord(QWidget *parent)
   : QWidget{parent},
   ui(new Ui::HistoryRecord)
{

     ui->setupUi(this);
    InitDatabase();

    qDebug()<<ACCOUNT;

    connect(ui->pushButton,&QPushButton::clicked,this,[=](){
        this->on_pushButton_clicked();
    });

}

void HistoryRecord::InitTable()
{
    setWindowTitle("历史记录");
    setFixedSize(686,605);

    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);       // 整行选中的方式
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);    // 设置为可以选中单个目标
    ui->tableWidget->verticalHeader()->setVisible(false);                       // 隐藏行表头
    ui->tableWidget->resizeRowsToContents();                                    // 行高与内容匹配
    ui->tableWidget->resizeColumnsToContents();
    ui->tableWidget->setRowCount(100);
//    ui->tableWidget->setColumnCount(5);
    ui->tableWidget->setColumnCount(4);

     QStringList headList;
//     headList << QString("时间") << QString("网站标题") << QString("网址") << QString("网站icon图标") << QString("删除记录");
     headList << QString("时间") << QString("网站标题") << QString("网址") << QString("删除记录");
     ui->tableWidget->setHorizontalHeaderLabels(headList);

    QHeaderView* widthlist = ui->tableWidget->horizontalHeader();
    widthlist->resizeSection(0, 145);									                                  // 设置列宽
    widthlist->resizeSection(1, 145);
    widthlist->resizeSection(2, 145);
    widthlist->resizeSection(3, 145);
//    widthlist->resizeSection(4, 120);

    QSqlQuery query;

    QString tempstring="default";
    if(ACCOUNT!="")     tempstring=ACCOUNT;

    Q(tempstring)

    QString sql=QString("select * from history where account = '%1' order by time desc").arg(tempstring);
    if(query.exec(sql))
    {
        Q("FLASH本地账户ACCOUNT历史成功")
        int i=0;
        while(query.next())
        {
            QString time=query.value(1).toString(), title=query.value(3).toString();
            QString url=query.value(4).toString(), iconUrl=query.value(2).toString();

            ui->tableWidget->setRowHeight(i , 64);
            QTableWidgetItem *item_index = new QTableWidgetItem (query.value(1).toString());
            ui->tableWidget->setItem(i,0,item_index);

            // QTableWidgetItem *item_index1 = new QTableWidgetItem (query.value(3).toString());
            // ui->tableWidget->setItem(i,1,item_index1);


        URL[i]=new QPushButton();
        URL[i]->setStyleSheet("QPushButton{text-align : left;}");
        URL[i]->setText(title);

        connect(URL[i],&QPushButton::clicked,this,[=](){
            this->open_one_record(i,url);
        });
        QHBoxLayout *vLayout1 = new QHBoxLayout();
        QWidget *Widget_btn1 = new QWidget;
        vLayout1->addWidget(URL[i]);
        Widget_btn1->setLayout(vLayout1);
        Widget_btn1->setStyleSheet("QWidget{ border: 0px }");//

        ui->tableWidget->setCellWidget(i,1,Widget_btn1);

            ///////////////////////


            QTableWidgetItem *item_index2 = new QTableWidgetItem (query.value(4).toString());
            ui->tableWidget->setItem(i,2,item_index2);

//            QTableWidgetItem *item_index3 = new QTableWidgetItem (query.value(2).toString());
//            ui->tableWidget->setItem(i,3,item_index3);




             DELETE[i]=new QPushButton();
             DELETE[i]->setText("删除(X)");
             connect(DELETE[i],&QPushButton::clicked,this,[=](){
                 this->delete_one_record(i,url,title);
                 DeleteRecordIfExists(title,url);
             });
             QHBoxLayout *vLayout = new QHBoxLayout();
             QWidget *Widget_btn = new QWidget;
             vLayout->addWidget(DELETE[i]);
             Widget_btn->setLayout(vLayout);
             Widget_btn->setStyleSheet("QWidget{ border: 0px }");//

             ui->tableWidget->setCellWidget(i,3,Widget_btn);


            i++;
        }
    }
    else
    {
        qDebug()<<query.lastError();
        Q("FLASH本地账户ACCOUNT历史失败")
    }
}

 void HistoryRecord::open_one_record(int i,QString url){
     qDebug()<<"开点"<<url<<" "<<url;
     emit sendData(url);
        this->close();
 }

 void HistoryRecord::delete_one_record(int i,QString url,QString title){
//     DeleteRecordIfExists(url,title);
     int rowIndex = ui->tableWidget->currentRow();  //查询选中行
         if (rowIndex > -1)
         {
             qDebug()<<"开删"<<url<<" "<<title;
             ui->tableWidget->removeRow(rowIndex);  //删除选中行
//             DeleteRecordIfExists(url,title);
         }
 }

void HistoryRecord::InitDatabase()
{
    QSqlDatabase db;
    if(QSqlDatabase::contains("qt_sql_default_connection"))
        db = QSqlDatabase::database("qt_sql_default_connection");
    else
        db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("../info.db");
    if(!db.open())
    {
        qDebug()<<"DB打不开";
        QMessageBox::critical(0,"错误","无法连接",QMessageBox::Yes);
    }
    QSqlQuery query(db);
    QString sql=QString("create table if not exists history("
                        // "history_id int,"
                        "account varchar(32) ,"
                        "time datetime primary key,"
                        "iconUrl varchar(256),"
                        "title varchar(256),"
                        "url varchar(256)"
                        ")");

    if(query.exec(sql))
    {
        qDebug()<<"历史记录表建立成功！！";
    }
    else
    {
        qDebug()<<query.lastError();
        qDebug()<<"历史记录表建立失败！！";
    }
}


void HistoryRecord::AddOneHistoryRecord(QString time,QString title,QString url)
{
    DeleteRecordIfExists(title,url);
    qDebug()<<"AddOneHistoryRecord"<<"   "<<time<<" "<<title<<" "<<url;
    QSqlQuery q;
    q.prepare("insert into history (account,time,iconUrl,title,url)"
                                  "values(:account,:time,:iconUrl,:title,:url)");

    qDebug()<<"ACCOUNT为"<<ACCOUNT;
    QString tempstring="default";
    if(ACCOUNT!="")          tempstring=ACCOUNT;
    qDebug()<<tempstring;

    q.bindValue(":account", tempstring);
    q.bindValue(":time",time);
    q.bindValue(":iconUrl","ICONURL");
    q.bindValue(":title",title);
    q.bindValue(":url",url);

    if(q.exec())
    {
        qDebug()<<"插入历史记录成功";
    }
    else
    {
        qDebug()<<q.lastError();
        qDebug()<<"插入历史记录失败";
    }
}

void HistoryRecord::DeleteRecordIfExists(QString title,QString url)
{
    QString tempstring="default";
    if(ACCOUNT!="")     tempstring=ACCOUNT;

    QSqlQuery query;

    query.prepare("delete from history where account=? and url=? and title=?");
    query.bindValue(0, tempstring);
    query.bindValue(1, url);
    query.bindValue(2, title);
    if(query.exec())
    {
        qDebug()<<"删除以更新已有记录成功";
    }
    else
    {
        qDebug()<<query.lastError();
        qDebug()<<"删除以更新已有记录失败";
    }
}

void HistoryRecord::ShowThisAccount()
{
    Q( QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") )

    QSqlQuery query;

    QString tempstring="default";
    if(ACCOUNT!="")     tempstring=ACCOUNT;

    QString sql=QString("select * from history where account = '%1' order by time desc").arg(tempstring);
    if(query.exec(sql))
    {
        Q("查询本地账户ACCOUNT历史成功")
        while(query.next())
        {
            qDebug() << query.value(0).toString() << query.value(1).toString()
                     << query.value(2).toString()<< query.value(3).toString()
                     << query.value(4).toString();
        }
    }
    else
    {
        qDebug()<<query.lastError();
        Q("查询本地账户ACCOUNT历史失败")
    }
}

void HistoryRecord::ShowAllHistory()
{
    Q( QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") )
    QSqlQuery query;
//    QString sql=QString("select * from history group by account order by time desc");
    QString sql=QString("select * from history");
    if(query.exec(sql))
    {
        Q("查询全部历史成功")
        while(query.next())
        {
            qDebug() << query.value(0).toString() << query.value(1).toString()
                     << query.value(2).toString()<< query.value(3).toString()
                     << query.value(4).toString();
        }
    }
    else
    {
        qDebug()<<query.lastError();
        Q("查询全部历史失败")
    }
}

void HistoryRecord::ModelShowAllHistory()
{
        QSqlQueryModel *model = new QSqlQueryModel;
//        model->setQuery("select * from history group by account order by time desc");
        QString sql=QString("select * from history");
        model->setHeaderData(0, Qt::Horizontal, tr("账户"));
        model->setHeaderData(1, Qt::Horizontal, tr("时间"));
        model->setHeaderData(2, Qt::Horizontal, tr("icon"));
        model->setHeaderData(3, Qt::Horizontal, tr("标题"));
        model->setHeaderData(4, Qt::Horizontal, tr("url"));
        QTableView *view = new QTableView;
        view->setModel(model);
        view->show();
}


void HistoryRecord::DeleteOneHistoryRecord(int id)
{
    QSqlQuery query;
    QString sql=QString("delete from history where history_id = '%1' and account = '%2'").arg((id,ACCOUNT));

    if(query.exec(sql))
    {
        qDebug()<<"DeleteOne SUCESS";
    }
    else
    {
        qDebug()<<query.lastError();
        qDebug()<<"DeleteOne Failure";
    }
}

void HistoryRecord::DeleteAllHistoryRecord()
{

    // QMessageBox message(QMessageBox::NoIcon,"询问","确定清空历史记录？", QMessageBox::Yes | QMessageBox::No, NULL);
    // if(message.exec() == QMessageBox::Yes)
    // {
        Q(ACCOUNT)
        QSqlQuery query;
        QString tempstring="default";if(ACCOUNT!="")   tempstring=ACCOUNT;
        QString sql=QString("delete from history where account = '%1'").arg(tempstring);
        if(query.exec(sql))
        {
            Q("删除本地ACCOUNT历史记录成功")
//                                QMessageBox::information(NULL, "消息","删除成功",QMessageBox::Ok);
//                                QLayoutItem* child;
//                                while ((child=layer->takeAt(0))!=0){
//                                    //setParent为NULL，防止删除之后界面不消失
//                                    if(child->widget()){
//                                        child->widget()->setParent(NULL);
//                                    }
//                                    delete child;
//                                }
//                                layer->setParent(NULL);
//                                delete layer;
        }
        else
        {
            qDebug()<<query.lastError();
            Q("删除本地ACCOUNT历史记录失败")
        }
//    }
    // else
    // {
    //     QMessageBox::information(NULL, "消息","出现未知错误，删除失败",QMessageBox::Ok);
    // }
}

void HistoryRecord::on_pushButton_clicked()
{
    DeleteAllHistoryRecord();
    this->close();
//    this->close();
}

HistoryRecord::~HistoryRecord()
{
    delete ui;
}


// historyrecord*  historyrecord::MakeObj()
// {
//     return &HistoryRecordObj;
// }
